<!-- 部门管理 部门列表组件 -->
<template>
    <div class="">
        <!-- 面包屑导航区域 -->
        <el-breadcrumb separator="/">
            <!-- <el-breadcrumb-item><a>用户管理</a></el-breadcrumb-item> -->
            <el-breadcrumb-item>分配用户</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 卡片视图区域 -->
        <el-card>
            <!-- 搜索区域 -->
            <el-form :model="queryInfo" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
                <el-form-item label="用户名称" prop="loginName">
                    <el-input v-model="queryInfo.loginName" placeholder="请输入用户名称" clearable />
                </el-form-item>
                <el-form-item label="手机号码" prop="phonenumber">
                    <el-input v-model="queryInfo.phonenumber" placeholder="请输入手机号码" clearable />
                </el-form-item>
                <el-form-item>
                    <el-button @click="handleQuery" type="primary" icon="el-icon-search" size="mini">搜索</el-button>
                    <el-button @click="resetQuery" icon="el-icon-refresh" size="mini">重置</el-button>
                </el-form-item>
            </el-form>

            <!-- 按钮区域 -->
            <el-row :gutter="10" class="mb8" style="marginBottom:20px">
                <el-col :span="1.5">
                    <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="addTypeHandle">添加用户</el-button>
                </el-col>
                <el-col :span="1.5">
                    <el-button type="warning" plain icon="el-icon-close" size="mini"
                        @click="closeViewHandler">关闭</el-button>
                </el-col>
            </el-row>
            <!-- 表格区域 -->
            <el-table :data="userList" style="width: 100%;margin-bottom: 20px;" row-key="id" default-expand-all
                :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
                <el-table-column prop="loginName" label="用户名称">
                </el-table-column>
                <el-table-column prop="userName" label="用户名称">
                </el-table-column>
                <el-table-column prop="email" label="邮箱">
                </el-table-column>
                <el-table-column prop="phonenumber" label="手机">
                </el-table-column>
                <el-table-column prop="status" label="状态">
                    <template slot-scope="scope">
                        <span :value="scope.row.status">{{ scope.row.status === '0' ? '正常' : '停用' }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" label="创建时间">
                </el-table-column>
                <el-table-column label="操作" align="center" width="220" class-name="small-padding fixed-width">
                    <template slot-scope="scope">
                        <el-button size="mini" type="text" icon="el-icon-edit"
                            @click="cancelAuthUser(scope.row)">取消授权</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页区域 -->
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="queryInfo.currentPage" :page-sizes="[10, 20, 30, 40]" :page-size="queryInfo.pageSize"
                layout="total, sizes, prev, pager, next, jumper" :total="total1">
            </el-pagination>
        </el-card>

        <!-- 添加权限用户 弹窗 -->
        <el-dialog title="选择用户" append-to-body width="840px" top="5vh" :visible.sync="dialogVisible"
            @close="addDialogClosed">
            <!-- 内容主题区域 -->
            <el-form ref="paramsForm" :model="queryParams" label-width="70px" size="small" :inline="true">
                <el-form-item label="用户名称" prop="loginName">
                    <el-input v-model="queryParams.loginName" placeholder="请输入用户名称" clearable />
                </el-form-item>
                <el-form-item label="手机号码" prop="phonenumber">
                    <el-input v-model="queryParams.phonenumber" placeholder="请输入手机号码" clearable />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQue">搜索</el-button>
                    <el-button icon="el-icon-refresh" size="mini" @click="resetQue">重置</el-button>
                </el-form-item>
            </el-form>
            <el-row>
                <el-table @row-click="clickRow" ref="table" :data="weiUserlist" :row-key="row => row.userId"
                    @selection-change="handleSelectionChange" height="260px">
                    <el-table-column type="selection" width="55" :reserve-selection="true" ></el-table-column>
                    <el-table-column label="用户名称" prop="loginName" :show-overflow-tooltip="true" />
                    <el-table-column label="用户名称" prop="userName" :show-overflow-tooltip="true" />
                    <el-table-column label="邮箱" prop="email" :show-overflow-tooltip="true" />
                    <el-table-column label="手机" prop="phonenumber" :show-overflow-tooltip="true" />
                    <el-table-column label="状态" align="center" prop="status">
                        <!-- <template slot-scope="scope">
                            <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status" />
                        </template> -->
                    </el-table-column>
                    <el-table-column label="创建时间" align="center" prop="createTime" width="180">
                        <!-- <template slot-scope="scope">
                            <span>{{ parseTime(scope.row.createTime) }}</span>
                        </template> -->
                    </el-table-column>
                </el-table>
                <el-pagination @size-change="handleSizeChanges" @current-change="handleCurrentChanges"
                    :current-page="queryParams.currentPage" :page-sizes="[10, 20, 30, 40]" :page-size="queryParams.pageSize"
                    layout="total, sizes, prev, pager, next, jumper" :total="total">
                </el-pagination>
            </el-row>
            <!-- 底部区域 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="handleSelectUser">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    // 组件名称
    name: '',
    // 局部注册的组件
    components: {},
    // 组件参数 接收来自父组件的数据
    props: {},
    // 组件状态值
    data() {
        // 验证邮箱的规则 自定义校验规则
        var checkEmail = (rule, value, cb) => {
            // 验证邮箱的正则表达式
            const regEmail = /^([a-zA-Z0-9])+@([a-zA-Z0-9])+(\.[a-zA-Z0-9_-])+/
            if (regEmail.test(value)) {
                // 合法的邮箱
                return cb()
            }
            cb(new Error('请输入合法的邮箱!'))
        }
        // 验证手机的规则queryParams
        var checkMobile = (rule, value, cb) => {
            // 验证手机号的规则
            const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
            if (regMobile.test(value)) {
                return cb()
            }
            cb(new Error('请输入合法的手机号!'))

        }
        return {
            userIds: [], // 选中的数据id
            showSearch: true,
            // 获取用户列表数据的参数对象
            queryInfo: {
                // 当前的页数
                currentPage: 1,
                // 当前每页显示多少条数据
                pageSize: 10,
                roleId: undefined,
                loginName: undefined, // 用户名
                phonenumber: undefined, // 手机号码
            },
            // 未分配列表
            queryParams: {
                currentPage: 1,
                pageSize: 10,
                roleId: undefined,
                loginName: undefined,
                phonenumber: undefined
            },
            userList: [],
            weiUserlist: [],
            total: 0,
            total1: 0,
            // 对话框显示与隐藏
            dialogVisible: false,
            dicId: undefined,
            // 添加用户的表单数据
            addForm: {
                roleId: this.$route.query.roleId,
                status: 1,
                dictLabel: undefined,
                dictSort: 0,
                dictValue: undefined,
                cssClass: undefined,
                listClass: undefined,
                radio: 1,
                remark: '',
                dictCode: undefined
            },
            // 用户导入参数
            upload: {
                // 是否显示弹出层（用户导入）
                open: false,
                // 弹出层标题（用户导入）
                title: '',
                // 是否禁用上传
                isUploading: false,
                // 是否更新已经存在的用户数据
                updateSupport: 0,
            },
            // 添加表单验证的校验规则对象
            addFormRules: {
                username: [
                    { required: true, message: '请输入用户名!', trigger: 'blur', },
                    { min: 3, max: 12, message: '用户名的长度在3~12个字符之间', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码!', trigger: 'blur', },
                    { min: 6, max: 15, message: '密码的长度在6~15个字符之间', trigger: 'blur' }
                ],
                email: [
                    { required: true, message: '请输入邮箱!', trigger: 'blur', },
                    { validator: checkEmail, trigger: 'blur', }
                ],
                mobile: [
                    { required: true, message: '请输入手机号!', trigger: 'blur', },
                    { validator: checkMobile, trigger: 'blur', }
                ],
            },
        }
    },
    // 计算属性
    computed: {},
    // 侦听器
    watch: {},
    // 生命周期钩子   注：没用到的钩子请自行删除
    /**
    * 组件实例创建完成，属性已绑定，但DOM还未生成，el属性还不存在
    */
    created() {
        this.getList()
        this.handleSizeChange()
        // this.handleCurrentChange()
    },
    /**
    * el 被新创建的 vm.el 替换，并挂载到实例上去之后调用该钩子。
    * 如果 root 实例挂载了一个文档内元素，当 mounted 被调用时 vm.el 也在文档内。
    */
    mounted() { },
    // 组件方法
    methods: {
        // 已分配用户列表
        async getList() {
            console.log(this.$route.query.roleId);
            this.queryInfo.roleId = this.$route.query.roleId
            const params = this.queryInfo
            const { data: res } = await this.$http.post('/sys-role/assignUserPage', params)
            if (res.code === 20000) {
                this.userList = res.data.records
                this.addForm.dictCode = res.data.records.dictCode
                console.log(res.data.total);
                this.total1 = parseInt(res.data.total)
            }
        },
        // 未分配用户列表
        async getWeiUserList() {
            this.queryParams.roleId = this.$route.query.roleId
            const param = this.queryParams
            const { data: res } = await this.$http.post('/sys-role/unAssignUserPage', param)
            if (res.code === 20000) {
                console.log(res.data.records);
                this.weiUserlist = res.data.records
                this.total = parseInt(res.data.total)
            } else {
                this.$message.error(res.msg)
            }
        },
        // 新增 弹窗
        addTypeHandle() {
            this.dialogVisible = true
            this.getWeiUserList()
            this.upload.title = "添加用户"
            console.log(1);
        },
        // 修改按钮操作
        updateData(row) {
            const dictId = row
            console.log(dictId);
            this.dicId = row
            this.dialogVisible = true
            this.upload.title = "修改用户"
        },
        /** 取消授权按钮操作 */
        async cancelAuthUser(row) {
            console.log(row);
            const uIds = row.userId
            const pId = {
                roleId: parseInt(this.$route.query.roleId),
                userIds: [uIds]
            }
            const { data: res } = await this.$http.post('/sys-role/unAssignUser', pId)
            if (res.code === 20000) {
                this.$message({
                    message: "取消授权成功",
                    type: "success",
                    center: true
                });
                this.getList()
            } else {
                this.$message.error(res.msg)
            }
        },
        /** 提交按钮 选择授权用户操作 */
        async handleSelectUser() {
            const userIds = this.userIds
            if (userIds == "") {
                // this.$modal.msgError("请选择要分配的用户");
                this.$message({
                    message: "请选择要分配的用户",
                    type: "error",
                    center: true
                });
                return;
            }
            const p = {
                roleId: this.$route.query.roleId,
                userIds
            }
            const { data: res } = await this.$http.post('/sys-role/assignUser', p)
            if (res.code === 20000) {
                this.$message({
                    message: "分配成功",
                    type: "success",
                    center: true
                });
                this.getWeiUserList()
                this.getList()
                this.dialogVisible = false
            } else {
                this.$message.error(res.msg)
            }
        },
        // 监听 pageSize 改变的事件
        handleSizeChange(newSize) {
            this.queryInfo.pageSize = newSize;
            this.getList()
        },
        // 监听页码值改变的事件
        handleCurrentChange(newPage) {
            this.queryInfo.currentPage = newPage
            this.getList()
        },
        // 未分配 监听 pageSize 改变的事件
        handleSizeChanges(newSize) {
            this.queryParams.pageSize = newSize;
            this.getWeiUserList()
        },
        // 未分配
        handleCurrentChanges(newPage) {
            this.queryParams.currentPage = newPage
            this.getWeiUserList()

        },
        // 关闭 返回到 定时任务页面
        closeViewHandler() {
            this.$router.push('/roles')
        },
        // 监听添加用户对话框关闭事件
        addDialogClosed() {
            // 重置表单
            // this.$refs['addFormRef'].resetFields()
            // this.$refs.addFormRef.resetFields()
            this.$refs.paramsForm.resetFields()
        },
        // 搜索按钮操作
        handleQuery() {
            this.queryInfo.currentPage = 1
            this.getList()
        },
        // 重置按钮操作
        resetQuery() {
            // this.resetForm('queryForm')
            // console.log(this) this指向$refs的是通过ref获得的实例对象loginFormRef
            this.$refs.queryForm.resetFields()
            this.handleQuery()
        },

        // 未分配弹窗搜索 按钮操作
        handleQue() {
            this.queryParams.currentPage = 1
            this.getWeiUserList()
        },
        // 重置按钮操作
        resetQue() {
            // this.$refs['paramsForm'].resetFields()
            this.$refs.paramsForm.resetFields()
            this.handleQue()
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.userIds = selection.map(item => item.userId);
        },

        clickRow(row) {
            this.$refs.table.toggleRowSelection(row);
        },
    }
}
</script>

<style scoped lang="less">
// 表格样式
.el-table {
    margin-top: 15px;
    font-size: 12px;
}
</style>
